"""
Redis工具类 - 基于连接池的实现
"""
import json
import time
from typing import Optional
from redis import Redis, ConnectionPool
from fastapi import APIRouter, Query
from fastapi.responses import JSONResponse

from utils.myredis import Mredis
from tools.baidu_ocr import ocr_idcard

# 创建路由器（用于身份证OCR相关的API）
router = APIRouter(prefix="/api/ocr", tags=["OCR识别"])


class MyRedis:
    """Redis工具类（基于连接池）"""
    
    def __init__(self, host='127.0.0.1', port=6379, db=0):
        """初始化Redis连接池"""
        self.pool = ConnectionPool(host=host, port=port, db=db)
        self.r = Redis(connection_pool=self.pool)

    def set_str(self, key, value):
        """设置字符串"""
        return self.r.set(key, value)

    def setex_str(self, key, times, value):
        """设置字符串（带过期时间）"""
        return self.r.setex(key, times, value)

    def setnx_str(self, key, value):
        """设置字符串（仅当key不存在时）"""
        return self.r.setnx(key, value)

    def str_incr(self, key, value=1):
        """自增"""
        return self.r.incr(key, value)

    def get_str(self, key):
        """获取字符串"""
        value = self.r.get(key)
        if value:
            return value.decode()
        return value

    def incr_str(self, key, count=1):
        """自增"""
        return self.r.incr(key, count)

    def decr_str(self, key, count=1):
        """自减"""
        return self.r.decr(key, count)

    def str_del(self, key):
        """删除字符串"""
        return self.r.delete(key)

    def hash_add(self, key, field, value):
        """添加Hash字段"""
        return self.r.hset(key, field, value)

    def hash_getall(self, key):
        """获取对象的所有属性"""
        return self.r.hgetall(key)

    def hash_getone(self, key, field):
        """获取对象的某个属性的值"""
        return self.r.hget(key, field)

    def hash_hdel(self, key, field):
        """删除对象的某个属性"""
        return self.r.hdel(key, field)

    def get_key(self, pattern):
        """模糊查询key"""
        return self.r.keys(pattern)

    def list_rpush(self, key, value):
        """从右侧push到列表"""
        return self.r.rpush(key, value)
    
    def list_lpush(self, key, value):
        """从左侧push到列表"""
        return self.r.lpush(key, value)

    def list_pop(self, key):
        """从左侧pop列表"""
        return self.r.lpop(key)

    def list_lrange(self, key, min, max):
        """获取列表范围内的元素"""
        return self.r.lrange(key, min, max)

    def list_len(self, key):
        """获取列表长度"""
        return self.r.llen(key)

    def list_del(self, key, field):
        """删除列表中的元素"""
        return self.r.lrem(key, -1, field)

    def list_rpoplpush(self, list1, list2):
        """从list1右侧pop，并push到list2左侧"""
        return self.r.rpoplpush(list1, list2)

    def zset_zadd(self, key, score, value):
        """添加有序集合元素"""
        mapping = {value: score}
        return self.r.zadd(key, mapping=mapping)

    def zset_zrem(self, key, value):
        """删除有序集合元素"""
        return self.r.zrem(key, value)

    def zset_zrangebyscore(self, key, min, max):
        """按分数范围获取有序集合元素"""
        return self.r.zrangebyscore(key, min, max)


# 创建全局Redis实例（使用utils中的Mredis，功能更完整）
r = Mredis()


# ============ FastAPI路由接口（身份证OCR相关）============

@router.get("/idcard/submit")
async def submit_idcard_url(url: str = Query(..., description="身份证图片URL")):
    """提交身份证图片URL到处理队列"""
    r.list_lpush('baidulist', url)  # 将URL添加到队列
    return JSONResponse({"code": 200, "msg": "正在处理中"})


@router.get("/idcard/result")
async def get_idcard_result(picurl: str = Query(..., description="身份证图片URL")):
    """获取身份证OCR识别结果"""
    result_str = r.get_str(picurl)  # 从Redis获取OCR结果
    
    if result_str:
        try:
            userinfo = json.loads(result_str)  # 解析JSON
            return JSONResponse({"code": 200, "userinfo": userinfo})
        except json.JSONDecodeError:
            return JSONResponse({"code": 500, "msg": "数据解析失败"})
    else:
        return JSONResponse({"code": 404, "msg": "识别结果不存在或处理中"})


# ============ 后台处理函数（需要在后台任务中调用）============

async def process_idcard_queue():
    """处理身份证OCR队列（后台任务）"""
    import requests
    
    while True:
        url = r.list_rpop('baidulist')  # 从队列右侧取出URL
        if url:
            if isinstance(url, bytes):
                url = url.decode()  # 转换为字符串
            
            try:
                response = requests.get(url, timeout=30)  # 下载图片
                response.raise_for_status()
                image_bytes = response.content
                
                result = ocr_idcard(image_bytes, side="front")  # 调用OCR识别
                r.set_str(url, json.dumps(result, ensure_ascii=False))  # 存储结果
                print(f"OCR处理完成: {url}")
            except Exception as e:
                print(f"OCR处理失败 {url}: {e}")
        
        time.sleep(1)  # 避免CPU占用过高
